<script setup>
import {
    Edit,
    Delete,
    Check,
    Search
} from '@element-plus/icons-vue'
import avatar from '@/assets/default.png'
import { ref } from 'vue'

//文章分类数据模型
const categorys = ref([])

//用户搜索时选中的分类id
const categoryId = ref('')

//事件等级
const levels = ref([
    {
        level: 0,
        name: '一般'
    },
    {
        level: 1,
        name: '紧急'
    },
    {
        level: 2,
        name: '重要'
    }
])
//事件完成状态
const completionStatus = ref([
    {
        completion: 0,
        name: '未完成'
    },
    {
        completion: 1,
        name: '已完成'
    },
    {
        completion: 2,
        name: '作废'
    }
])
const rules = {
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择文章分类', trigger: 'blur' }
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'blur' }
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'blur' }
    ],
    level: [
        { required: true, message: '请选择文章等级', trigger: 'blur' }
    ],
    completion: [
        { required: true, message: '请选择文章完成状态', trigger: 'blur' }
    ]
}

//用户搜索时选中的发布状态
const state = ref('')

//文章列表数据模型
const articles = ref([])

//分页条数据模型
const total = ref(20)//总条数


//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    queryParams.value.pageSize = size
    articleList();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    queryParams.value.pageNum = num
    articleList();
}

import { articleCategoryListService, articleListService, articleAddService, articleUpdateService, articleDeleteService, articleDetailService } from '@/api/article';
//回显文章分类
const articleCategoryList = async () => {
    let result = await articleCategoryListService();
    categorys.value = result.data;
}
articleCategoryList();

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    status: null,
    level: null,
    completion: null,
    title: null
})
//获取文章数据
const articleList = async () => {
    //调用接口
    let result = await articleListService(queryParams.value);
    //渲染视图
    total.value = result.data.total;
    articles.value = result.data.items;

    //处理数据，给数据模型拓展一个属性categoryName
    for (let i = 0; i < articles.value.length; i++) {
        let article = articles.value[i];
        for (let j = 0; j < categorys.value.length; j++) {
            if (article.categoryId == categorys.value[j].id) {
                article.categoryName = categorys.value[j].categoryName;
            }
        }
    }
}
articleList();

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
//控制抽屉是否显示
const visibleDrawer = ref(false)
const viewOpen = ref(false)
//添加表单数据模型
const articleModel = ref({
    title: '',
    categoryId: '',
    imageUrl: '',
    content: '',
    status: '',
    startTime: '',
    endTime: '',
    level: '',
    completion: ''
})

//重置数据模式
function reset() {
    articleModel.value = {
        title: null,
        categoryId: null,
        imageUrl: null,
        content: null,
        status: null,
        startTime: null,
        endTime: null,
        level: null,
        completion: null
    }
}

//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

import { ElMessage, ElMessageBox } from 'element-plus';
//上传成功的回调函数
const uploadSuccess = (result) => {
    articleModel.value.imageUrl = result.data;
}

//添加文章
const addArticle = async (clickState) => {
    //把发布状态赋值给数据模型
    articleModel.value.status = clickState;

    //调用接口
    let result = await articleAddService(articleModel.value);
    ElMessage.success(result.msg ? result.msg : '添加成功');
    //抽屉消失
    visibleDrawer.value = false;
    //刷新当前列表
    articleList();
}

const title = ref('');
//回显文章数据
const showArticle = (row) => {
    articleDetailService(row.id).then(result => {
        articleModel.value = result.data;
    })
    title.value = '编辑事件';
    visibleDrawer.value = true;
}
const viewArticle = (row) => {
    articleDetailService(row.id).then(result => {
        articleModel.value = result.data;
    })
    title.value = '事件详情';
    viewOpen.value = true;
}

//重新编辑文章
const updateArticle = async (clickState) => {
    //把发布状态赋值给数据模型
    articleModel.value.status = clickState;

    //调用接口
    let result = await articleUpdateService(articleModel.value);
    ElMessage.success(result.msg ? result.msg : '修改成功')

    //关闭抽屉，刷新列表
    visibleDrawer.value = false;
    articleList();
}
//确认完成任务
const confirmCompletion = (row) => {
    articleModel.value = row;
    ElMessageBox.confirm(
        '确认完成该任务吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户确认完成 调用更新接口
            articleModel.value.completion = 1;
            let result = await articleUpdateService(articleModel.value)
            ElMessage({
                type: 'success',
                message: '修改成功',
            })
            //刷新列表
            articleList();
            reset();
        })
}

//删除文章
const deleteArticle = (row) => {
    //提示用户确认框 Element组件
    ElMessageBox.confirm(
        '确认删除该文章吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户确认删除 调用删除接口
            let result = await articleDeleteService(row.id)
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            //刷新列表
            articleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消了删除',
            })
        })
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.value = {
        categoryId: null,
        status: null,
        level: null,
        completion: null,
        title: null
    }
    handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    queryParams.value.pageSize = 10;
    articleList();
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>事件管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; reset(); title = '添加事件'">添加事件</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline :model="queryParams" ref="queryRef">
            <el-form-item label="标题：" style="width: 180px;">
                <el-input v-model="queryParams.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="事件分类：" style="width: 180px;">
                <el-select placeholder="请选择" v-model="queryParams.categoryId">
                    <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="级别：" style="width: 180px;">
                <el-select placeholder="请选择" v-model="queryParams.level">
                    <el-option v-for="level in levels" :key="level.level" :label="level.name"
                        :value="level.level"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="完成状态：" style="width: 180px;">
                <el-select placeholder="请选择" v-model="queryParams.completion">
                    <el-option v-for="c in completionStatus" :key="c.completion" :label="c.name"
                        :value="c.completion"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发布状态：" style="width: 180px;">
                <el-select placeholder="请选择" v-model="queryParams.status">
                    <el-option label="已发布" value="已发布"></el-option>
                    <el-option label="草稿" value="草稿"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <el-form>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="articles" style="width: 100%">
            <el-table-column label="文章标题" width="300" prop="title"></el-table-column>
            <el-table-column label="分类" prop="categoryName"></el-table-column>
            <el-table-column label="开始时间" prop="startTime">

            </el-table-column>
            <el-table-column label="结束时间" prop="endTime"> </el-table-column>
            <el-table-column label="事件级别" prop="level">
                <template #default="scope">
                    <el-tag v-if="scope.row.level == 0" type="success">一般</el-tag>
                    <el-tag v-else-if="scope.row.level == 2" type="warning">重要</el-tag>
                    <el-tag v-else type="danger">紧急</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="完成状态" prop="completion">
                <template #default="scope">
                    <el-tag v-if="scope.row.completion == 1" type="success">已完成</el-tag>
                    <el-tag v-else-if="scope.row.completion == 0" type="danger">未完成</el-tag>
                    <el-tag v-else type="info">作废</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status"></el-table-column>
            <el-table-column label="操作" width="200px">
                <template #default="{ row }">
                    <el-button :icon="Check" circle plain type="success" @click="confirmCompletion(row)"></el-button>
                    <el-button :icon="Search" circle plain type="Search" @click="viewArticle(row)"></el-button>
                    <el-button :icon="Edit" circle plain type="primary" @click="showArticle(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 15, 20, 30]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px" :rules="rules">
                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="文章分类" prop="category">
                    <el-select placeholder="请选择" v-model="articleModel.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文章封面">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
                        <img v-if="articleModel.imageUrl" :src="articleModel.imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="文章内容">
                    <div class="editor">
                        <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                        </quill-editor>
                    </div>
                </el-form-item>
                <!-- 选择时间 -->
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker v-model="articleModel.startTime" type="datetime" placeholder="选择日期"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker v-model="articleModel.endTime" type="datetime" placeholder="选择日期"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <!-- 选择事件级别 -->
                <el-form-item label="事件级别" prop="level">
                    <el-select v-model="articleModel.level" placeholder="请选择">
                        <el-option v-for="level in levels" :key="level.level" :label="level.name"
                            :value="level.level"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否完成" prop="completion">
                    <el-select v-model="articleModel.completion" placeholder="请选择">
                        <el-option v-for="c in completionStatus" :key="c.completion" :label="c.name"
                            :value="c.completion"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        @click="title == '添加事件' ? addArticle('已发布') : updateArticle('已发布')">发布</el-button>
                    <el-button type="info"
                        @click="title == '添加事件' ? addArticle('草稿') : updateArticle('草稿')">草稿</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <el-drawer v-model="viewOpen" :title="title" direction="rtl" size="50%">
            <!-- 查看文章表单 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="文章标题">
                    <span>{{ articleModel.title }}</span>
                </el-form-item>
                <el-form-item label="文章分类">
                    <template v-for="c in categorys">
                        <span v-if="articleModel.categoryId == c.id">{{ c.categoryName }}</span>
                    </template>
                </el-form-item>
                <el-form-item label="文章封面">
                    <img v-if="articleModel.imageUrl" :src="articleModel.imageUrl ? articleModel.imageUrl : avatar " class="avatar" style="width: 300px;"/>
                    <img v-else :src="avatar" class="avatar" style="width: 150px;"/>
                </el-form-item>
                <el-form-item label="文章内容">
                    <div class="editor" v-html="articleModel.content"></div>
                </el-form-item>
                <!-- 选择时间 -->
                <el-form-item label="开始时间">
                    <span>{{ articleModel.startTime }}</span>
                </el-form-item>
                <el-form-item label="结束时间">
                    <span>{{ articleModel.endTime }}</span>
                </el-form-item>
                <!-- 选择事件级别 -->
                <el-form-item label="事件级别">
                    <template v-for="level in levels">
                        <span v-if="articleModel.level == level.level">{{ level.name }}</span>
                    </template>
                </el-form-item>
                <el-form-item label="是否完成">
                    <template v-for="c in completionStatus">
                        <span v-if="articleModel.completion == c.completion">{{ c.name }}</span>
                    </template>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        @click="viewOpen = false">返回</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>